package de.herberlin.webapp.user.action;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import de.herberlin.webapp.core.AbstractAction;
import de.herberlin.webapp.db.Service;
import de.herberlin.webapp.user.User;

public class LoginAction extends AbstractAction {

	private static final long serialVersionUID = 1L;
	private String username,password;

	@Validate(required=true)
	public void setPassword(String password) {
		this.password = password;
	}

	@Validate(required=true)
	public void setUsername(String username) {
		this.username = username;
	}
	public LoginAction() {
	}
	@ValidationMethod
	public void validate(ValidationErrors errors) {
		User user=(User)Service.getItem(User.class, username);
		if (user == null) {
			errors.add("username", new SimpleError("Username not matching",null));
			logger.debug("User unknown: "+username);
		} else if (user.getPassword() == null || !user.getPassword().equals(password)) {
			errors.add("password", new SimpleError("Password not matching",null));
			logger.debug("Password not matching!");
		} else {
			user.setLoggedIn(true);
			getContext().getRequest().getSession().setAttribute(User.MY_SCOPE_NAME, user);
			logger.debug("User "+ user +" successfully logged in.");
		}
		
	}
	
	@DefaultHandler
	public Resolution perform() {

		return new ForwardResolution("/");
	}

}
